<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div style="padding: 10px;">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table
        :data="roleList"
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          align="center"
          label="角色"
          width="200"
        >
          <template #default="data">
            <el-input v-if="data.row.isEdit" v-model="data.row.cacheData.name" size="mini" />
            <span v-else>{{ data.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          align="center"
          label="启用"
          width="200"
        >
          <template #default="data">
            <el-switch v-if="data.row.isEdit" v-model="data.row.cacheData.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ data.row.state === 1 ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          align="center"
          label="描述"
        >
          <template #default="data">
            <el-input v-if="data.row.isEdit" v-model="data.row.cacheData.description" type="textarea" size="mini" />
            <span v-else>{{ data.row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
        >
          <template #default="data">
            <template v-if="!data.row.isEdit">
              <el-button size="middle" type="text" @click="btnPermission(data.row.id)">分配权限</el-button>
              <el-button size="middle" type="text" @click="editRole(data.row)">编辑</el-button>
              <el-popconfirm
                style="margin-left: 10px;"
                title="确定删除该角色信息吗？"
                @onConfirm="delRole(data.row.id)"
              >
                <template #reference>
                  <el-button size="middle" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button type="primary" size="mini" @click="editSubmit(data.row)">确定</el-button>
              <el-button size="mini" @click="editCancel(data.row)">取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px;">
        <el-pagination
          layout="prev, pager, next"
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 新增功能弹层 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="cancel">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="formModel" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="formModel.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch v-model="formModel.state" active-value="1" inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="formModel.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="submitRole">确定</el-button>
              <el-button size="mini" @click="cancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="permTree"
        node-key="id"
        check-strictly
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionListApi } from '@/api/permission'
import { addRoleApi, assignPermissionApi, deleteRoleApi, editRoleApi, getRoleDetailApi, getRoleListApi } from '@/api/role'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      formModel: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          {
            min: 1, max: 8, message: '角色名称长度为1-8个字符', trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ],
        state: []
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null, // 当前点击分配权限的角色id
      defaultCheckedKeys: [] // 默认选中的节点
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleListApi(this.pageParams)
      this.roleList = rows
      this.roleList.forEach(item => {
        // 给每一行数据添加一个编辑状态
        // item.isEdit = false
        // 改为响应式添加属性
        this.$set(item, 'isEdit', false)
        // 给每行添加一个编辑状态下的缓存数据, 用于点击编辑进行数据回显
        this.$set(item, 'cacheData', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    changePage(nowPage) {
      this.pageParams.page = nowPage
      this.getRoleList()
    },
    cancel() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    submitRole() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          await addRoleApi(this.formModel)
          this.$message.success('新增成功')
          this.cancel()
          this.getRoleList()
        }
      })
    },
    editRole(row) {
      row.isEdit = true
      // 每次点击编辑，重置缓存数据
      row.cacheData = {
        name: row.name,
        state: row.state,
        description: row.description
      }
    },
    editCancel(row) {
      row.isEdit = false
    },
    async editSubmit(row) {
      if (row.cacheData.name && row.cacheData.description) {
        await editRoleApi({ id: row.id, ...row.cacheData })
        this.$message.success('编辑成功')
        this.editCancel(row)
        // 更新数据
        Object.assign(row, { ...row.cacheData }) // 规避eslint的误判
      } else {
        this.$message.error('请输入角色名称和角色描述')
      }
    },
    async delRole(id) {
      await deleteRoleApi(id)
      this.$message.success('删除成功')
      // 如果删除时，当前页面只有一条数据，则跳转到上一页
      if (this.roleList.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetailApi(id)
      // console.log(permIds)
      this.defaultCheckedKeys = permIds // 默认选中的节点
      this.permissionData = transListToTreeData(await getPermissionListApi(), 0)
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      await assignPermissionApi({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
